/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.seppiko.pigeon.services;

import java.util.ArrayList;
import java.util.List;
import org.seppiko.pigeon.mapper.RoleMapper;
import org.seppiko.pigeon.mapper.UserMapper;
import org.seppiko.pigeon.models.RoleEntity;
import org.seppiko.pigeon.models.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author Leonard Woo
 */
@Service
public class UserService implements UserDetailsService {

  @Autowired
  private UserMapper userMapper;

  @Autowired
  private RoleMapper roleMapper;

  @Autowired
  private PasswordEncoder passwordEncoder;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    UserEntity user = userMapper.queryUserByUserName(username);
    if (username == null){
      throw new UsernameNotFoundException("User does not exist");
    }

    List<RoleEntity> roles = roleMapper.query(user.getUid());
    List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
    roles.forEach(role -> {
      authorityList.add(new SimpleGrantedAuthority(role.getName()));
    });

    return new User(user.getUsername(), user.getPassword(),
        true, true, true, true,
        authorityList);
  }

  public boolean changePassword(String username, String oldPassword, String newPassword) {
    UserEntity user = userMapper.queryUserByUserName(username);
    if( passwordEncoder.matches(oldPassword, user.getPassword()) ) {
      newPassword = passwordEncoder.encode(newPassword);
      return userMapper.changePassword(username, newPassword) > 0;
    }
    return false;
  }
}
